﻿using System;
using System.Drawing;
using System.Windows.Forms;
using SSAT.Utils;

namespace SSAT.Controls
{
    public partial class ConsoleField : UserControl
    {
        private Color _greetingColor = Color.Violet;
        private Color _errorColor = Color.Red;
        private Color _foregroundColor = Color.Black;
        private Color _infoColor = Color.Green;

        public Color InfoColor
        {
            get { return _infoColor; }
            set { _infoColor = value; }
        }

        public Color GreetingColor
        {
            get { return _greetingColor; }
            set { _greetingColor = value; }
        }

        public Color ErrorColor
        {
            get { return _errorColor; }
            set { _errorColor = value; }
        }

        public Color ForegroundColor
        {
            get { return _foregroundColor; }
            set { _foregroundColor = value; }
        }

        public ConsoleField()
        {
            InitializeComponent();
            SetupConsoleStreams();
        }

        private void SetupConsoleStreams()
        {
            Console.SetOut(new ConsoleFieldOutStream(Write));
        }

        public void Write(string text)
        {
            UIHelper.InvokeSafely(rtbConsole, delegate
            {
                int startIndex = rtbConsole.Text.Length - 1;
                startIndex = startIndex < 0 ? 0 : startIndex;
                rtbConsole.AppendText(text);
                rtbConsole.Select(startIndex, text.Length);
                rtbConsole.SelectionColor = _foregroundColor;
                rtbConsole.Select(rtbConsole.Text.Length - 1, 0);
            });
        }

        public void WriteLine(string text)
        {
            Write(text + Environment.NewLine);
        }

        public void WriteLine(string text, Color color)
        {
            Color old = ForegroundColor;
            try
            {
                ForegroundColor = color;
                WriteLine(text);
            }
            finally
            {
                ForegroundColor = old;
            }
        }

        public void WriteGreeting(string greeting)
        {
            WriteLine(greeting, GreetingColor);
        }

        public void WriteError(string error)
        {
            WriteLine(error, ErrorColor);
        }

        public void WriteInfo(string info)
        {
            WriteLine(info, InfoColor);
        }

        public void Clear()
        {
            UIHelper.InvokeSafely(rtbConsole, delegate { rtbConsole.Clear(); });
        }
    }
}
